package com.beyondsoft.sabg.edu.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.word.TableUtil;
import com.beyondsoft.sabg.edu.model.exception.WordGenerateException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;
import org.apache.poi.wp.usermodel.HeaderFooterType;
import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.impl.xb.xmlschema.SpaceAttribute;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @Author Mo cr
 * @Date 2024/1/25
 */
public class WordUtils {

    public static void createTitle(XWPFDocument docxDocument, String title, Boolean needReturn) {
        XWPFParagraph firstParagraphX = docxDocument.createParagraph();
        firstParagraphX.setAlignment(ParagraphAlignment.CENTER);
        XWPFRun runTitle = firstParagraphX.createRun();
        runTitle.setText(title);
        runTitle.setBold(true);
        runTitle.setFontSize(15);
        runTitle.setFontFamily("宋体");
        if (needReturn) {
            runTitle.addCarriageReturn();//回车键
        }
        runTitle.setKerning(15);//字间距
    }

    /**
     * word单元格列合并
     *
     * @param table     表格
     * @param row       合并列所在行
     * @param startCell 开始列
     * @param endCell   结束列
     * @atuh wangshenlong@beyondsoft.com
     */
    public static void mergeCellsHorizontal(XWPFTable table, int row, int startCell, int endCell) {
        for (int i = startCell; i <= endCell; i++) {
            XWPFTableCell cell = table.getRow(row).getCell(i);
            if (i == startCell) {
                // The first merged cell is set with RESTART merge value
                cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
            } else {
                // Cells which join (merge) the first one, are set with CONTINUE
                cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
            }
        }
    }

    /**
     * word单元格行合并
     *
     * @param table    表格
     * @param col      合并行所在列  0开始
     * @param startRow 开始行
     * @param endRow   结束行
     * @atuh wangshenlong@beyondsoft.com
     */
    public static void mergeCellsVertically(XWPFTable table, int col, int startRow, int endRow) {
        for (int i = startRow; i <= endRow; i++) {
            XWPFTableCell cell = table.getRow(i).getCell(col);
            if (i == startRow) {
                // The first merged cell is set with RESTART merge value
                cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
            } else {
                // Cells which join (merge) the first one, are set with CONTINUE
                cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
            }
        }
    }

    public static void textAlignCenterCell(XWPFTableCell cell) {
        //设置列文字居中
        CTTc cttc = cell.getCTTc();
        CTTcPr ctPr = cttc.addNewTcPr();
        ctPr.addNewVAlign().setVal(STVerticalJc.CENTER);
        cttc.getPList().get(0).addNewPPr().addNewJc().setVal(STJc.CENTER);
    }

    public static void textAlignCenterLeft(XWPFTableCell cell) {
        //设置列文字居中
        CTTc cttc = cell.getCTTc();
        CTTcPr ctPr = cttc.addNewTcPr();
        ctPr.addNewVAlign().setVal(STVerticalJc.TOP);
        cttc.getPList().get(0).addNewPPr().addNewJc().setVal(STJc.LEFT);
    }

    public static void cellCenterLeft(XWPFTable table, int row, int cell) {
        table.getRow(row).getCell(cell).getParagraphs().get(0).setAlignment(ParagraphAlignment.LEFT);
    }

    /**
     * 创建第一列的子标题与样式
     *
     * @param table
     * @param height
     * @param tableTitle
     * @return
     */
    public static XWPFTableRow createSubtitle(XWPFTable table, int height, String tableTitle) {
        XWPFTableRow row = table.createRow();
        row.setHeight(height);
        XWPFTableCell cell = TableUtil.getOrCreateCell(row, 0);
        cell.setWidth("6%");
        XWPFRun run = cell.getParagraphs().get(0).createRun();
        run.setText(tableTitle);
        run.setBold(true);
        return row;
    }

    /**
     * 设置表格所有列文字居中
     *
     * @param table
     * @atuh wangshenlong@beyondsoft.com
     */
    public static void centerTextInTable(XWPFTable table) {
        centerTextInTable(table, table.getRows().size());
    }

    /**
     * 设置表格指定结束行
     *
     * @param table
     * @atuh wangshenlong@beyondsoft.com
     */
    public static void centerTextInTable(XWPFTable table, int endRow) {
        for (int row = 0; row < endRow; row++) {
            for (int col = 0; col < table.getRow(row).getTableCells().size(); col++) {
                XWPFTableCell cell = table.getRow(row).getCell(col);
                // 设置文字剧中
                CTTc cttc = cell.getCTTc();
                CTTcPr ctPr = cttc.addNewTcPr();
                ctPr.addNewVAlign().setVal(STVerticalJc.CENTER);
                cttc.getPList().get(0).addNewPPr().addNewJc().setVal(STJc.CENTER);
            }
        }
    }

    public static void insertImageInTableCell(XWPFTableCell cell, String imagePath) {
        insertImageInTableCell(cell, imagePath, 40, 25);
    }

    /**
     * 插入图片
     *
     * @param cell
     * @param imagePath
     * @param width
     * @param height
     * @throws Exception
     */
    public static void insertImageInTableCell(XWPFTableCell cell, String imagePath, int width, int height) {
        if (StrUtil.isBlank(imagePath)) {
            return;
        }
        // 创建段落
        XWPFParagraph paragraph = cell.addParagraph();
        // 创建运行对象
        XWPFRun run = paragraph.createRun();
        // 插入图片
        FileInputStream imageStream = null;
        try {
            imageStream = new FileInputStream(imagePath);
            run.addTab();
            run.addPicture(imageStream, XWPFDocument.PICTURE_TYPE_JPEG, imagePath, Units.toEMU(width), Units.toEMU(height));
            run.addBreak();
            imageStream.close();
        } catch (InvalidFormatException | IOException e) {
            throw new WordGenerateException("insert image failed");
        }
    }

    /**
     * 添加页脚页码以及备注
     * @param document
     * @param remark
     */
    public static void addPageFooter(XWPFDocument document, String remark){
        XWPFHeaderFooterPolicy policy = document.getHeaderFooterPolicy() == null
                ? document.createHeaderFooterPolicy()
                : document.getHeaderFooterPolicy();

        // 创建页脚并设置内容
        XWPFFooter footer = policy.createFooter(XWPFHeaderFooterPolicy.DEFAULT);
        XWPFParagraph paragraph = footer.createParagraph();
        paragraph.setAlignment(ParagraphAlignment.RIGHT);

        // 在页脚中添加页码
        XWPFRun run = paragraph.createRun();
        run.setText(remark+"-");
        run.getCTR().addNewFldChar().setFldCharType(org.openxmlformats.schemas.wordprocessingml.x2006.main.STFldCharType.BEGIN);
        run.getCTR().addNewInstrText().setStringValue("PAGE");
        run.getCTR().addNewFldChar().setFldCharType(org.openxmlformats.schemas.wordprocessingml.x2006.main.STFldCharType.SEPARATE);
        run.getCTR().addNewT().setStringValue("1");
        run.getCTR().addNewFldChar().setFldCharType(org.openxmlformats.schemas.wordprocessingml.x2006.main.STFldCharType.END);

        run.setText("/");
        run.getCTR().addNewFldChar().setFldCharType(org.openxmlformats.schemas.wordprocessingml.x2006.main.STFldCharType.BEGIN);
        run.getCTR().addNewInstrText().setStringValue("NUMPAGES");
        run.getCTR().addNewFldChar().setFldCharType(org.openxmlformats.schemas.wordprocessingml.x2006.main.STFldCharType.SEPARATE);
        run.getCTR().addNewT().setStringValue("1");
        run.getCTR().addNewFldChar().setFldCharType(org.openxmlformats.schemas.wordprocessingml.x2006.main.STFldCharType.END);

    }
}
